package example;

import example.service.BaseService;
import example.servlet.UserFilter;
import example.servlet.UserListener;
import example.servlet.UserServlet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.HandlesTypes;

import java.util.EnumSet;
import java.util.Set;

/**
 * Servlet 3.0 的运行时插件机制
 *
 */
@HandlesTypes(value = {BaseService.class})
public class WebInitializer implements ServletContainerInitializer {
    /**
     * 容器启动的时候，会执行onStartup方法
     * @param set 容器启动，会把@HandlesTypes(value = {BaseService.class}).BaseService这个类的
     * 子类传入（实现类，子接口），但不包含BaseService本类
     */
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        System.out.println("容器启动！");
        //获取到了BaseService 类型的全部子类型
        System.out.println(set);

        //容器启动后注入组件，！！！只有在项目启动时或在监听器内，才能向容器内添加组件，运行时是无法注入组件的
        ServletRegistration.Dynamic servlet = servletContext.addServlet("UserServlet", UserServlet.class);
        servlet.addMapping("/user");

        servletContext.addListener(UserListener.class);

        FilterRegistration.Dynamic filter = servletContext.addFilter("UserFilter", UserFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
    }
}


